package com.oem.fragment;

import static com.oem.fragment.contant.URLConstant.USER_URL;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.oem.fragment.config.RetrofitClient;
import com.oem.fragment.model.Result;
import com.oem.fragment.model.user.User;
import com.oem.fragment.service.UserService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;


public class ProfileFragment extends Fragment {

    private TextView tvName, tvEmail, tvPhone, tvAddress, tvBirthday, tvLastLogin;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);

        tvName = view.findViewById(R.id.tvName);
        tvEmail = view.findViewById(R.id.tvEmail);
        tvPhone = view.findViewById(R.id.tvPhone);
        tvAddress = view.findViewById(R.id.tvAddress);
        tvBirthday = view.findViewById(R.id.tvBirthday);
        tvLastLogin = view.findViewById(R.id.tvLastLogin);

        loadUserInfo(1L); // mock 用户ID = 1

        return view;
    }

    private void loadUserInfo(Long userId) {
        Retrofit retrofit = RetrofitClient.getClient(USER_URL);
        UserService userService = retrofit.create(UserService.class);

        userService.getUserInfo(userId).enqueue(new Callback<Result<User>>() { // Specify Result<User>
            @Override
            public void onResponse(Call<Result<User>> call, Response<Result<User>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    User user = response.body().getData();
                    tvName.setText("姓名：" + user.getName());
                    tvEmail.setText("邮箱：" + user.getEmail());
                    tvPhone.setText("电话：" + user.getPhone());
                    tvAddress.setText("地址：" + user.getAddress());
                    tvBirthday.setText("生日：" + user.getDateOfBirth());
                    tvLastLogin.setText("上次登录：" + user.getLastLoginTime());
                } else {
                    Toast.makeText(getContext(), "获取用户失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Result<User>> call, Throwable t) {
                Toast.makeText(getContext(), "网络异常: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

